package com.nchu.react.webflux.action;

import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;

import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author fujianjian
 * @project react-learning
 * @date 2018/9/21 下午2:06
 */

//@RestController
public class WebFluxAction {


    @GetMapping("/geet")
    public Mono<String> geet() {
        return Mono.just("Hello world for reactive web");
    }


    @GetMapping("/randomNumber")
    public Flux<ServerSentEvent<Integer>> randomNumbers() {
        return Flux.interval(Duration.ofSeconds(2))
                .map(seq -> Tuples.of(seq, ThreadLocalRandom.current().nextInt()))
                .map(data -> ServerSentEvent.<Integer>builder()
                        .event("random number sender")
                        .comment("定时推送一个随机数到客户端")
                        .id(Long.toString(data.getT1()))
                        .data(data.getT2())
                        .build());
    }
}
